package com.wuwangfu.state;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author: jcshen
 * @Date: 2023-03-03
 * @PackageName: com.wuwangfu.state
 * @ClassName: KeyedStateByInteger
 * @Description: valuestate 底层源码解析
 * @Version: 1.0.0
 *
 * 使用一个Integer类型的成员变量来记录状态
 * 会存在一个问题，就是 同一个分区同一个分组的不同key的值会累加，这就会造成分辨不出来具体 key的累加了
 *
 */
public class KeyedStateByInteger {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //
        env.enableCheckpointing(10000);
        //重启策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,5000));
        //source
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);
        //transform
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = line.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    if ("error".equals(word)) {
                        throw new RuntimeException("报错拉");
                    }
                    collector.collect(Tuple2.of(word, 1));
                }
            }
        });
        //分组
        KeyedStream<Tuple2<String, Integer>, Integer> keyed = wordAndCount.keyBy(t -> t.f1);
        //state
        keyed.map(new RichMapFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            //成员变量
            private Integer counter = 0;

            @Override
            public Tuple2<String, Integer> map(Tuple2<String, Integer> input) throws Exception {
                String word = input.f0;
                Integer count = input.f1;
                //累加
                counter += count;
                //赋值
                input.f1 = counter;
                //返回
                return input;
            }
        }).print();

        env.execute();
    }
}
